﻿using Newtonsoft.Json;
using Omabar.BLL;
using Omabar.Common;
using Omabar.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;

namespace Omabar.CMS.Handler
{
    /// <summary>
    /// CityBelongRead 的摘要说明
    /// </summary>
    public class CityBelongRead : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                context.Response.ContentType = "text/plain";
                int pageNo = int.Parse(context.Request["page"]);
                string keywords = context.Request["key"];

                string sqllist = "SELECT TOP 10 ROUTE_ID,ROUTE_CONTINENT,ROUTE_COUNTRY_NAME,ROUTE_CITY FROM (SELECT ROW_NUMBER() OVER(ORDER BY ROUTE_CITY DESC) AS ROWNUMBER,* FROM (SELECT '0' as ROUTE_ID, CITY_NAME AS ROUTE_CITY,COUNTRY_NAME AS ROUTE_COUNTRY_NAME,T.BELONG AS ROUTE_CONTINENT FROM CITY C LEFT JOIN COUNTRY T ON C.BELONG=T.COUNTRY_NAME) Z {0}) A WHERE ROWNUMBER > {1}";
                string sqlcount = "select count(*) from CITY";
                if (!string.IsNullOrEmpty(keywords))
                {
                    string filter = string.Format(" where ROUTE_CITY like '%{0}%'", keywords);
                    sqlcount += filter;
                    sqllist = string.Format(sqllist, filter, (pageNo - 1) * 10);
                }

                sqllist = string.Format(sqllist, keywords, (pageNo - 1) * 10);

                CityBelong_BLL bll = new CityBelong_BLL();
                int total = bll.GetCount(sqlcount);
                List<ROUTE_COUNTRY> rcs = bll.GetModels(sqllist);
                Paginator<ROUTE_COUNTRY> paginator = new Paginator<ROUTE_COUNTRY>();
                paginator.total = total;
                paginator.list = rcs;

                context.Response.Write(JsonConvert.SerializeObject(paginator));
            }
            catch (Exception ex)
            {
                Tom.Net.Log.LogManager.Error("读取城市失败", ex);
                context.Response.Write("{\"count\":0,\"list\":[]}");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}